<template>
  <div class="profile-container">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="8" :md="6">
        <el-card class="profile-sidebar">
          <div class="user-avatar">
            <el-avatar :size="100" :src="userAvatarUrl"></el-avatar>
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :headers="uploadHeaders"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <el-button size="small" type="primary">更换头像</el-button>
            </el-upload>
          </div>
          
          <div class="user-info-summary">
            <h3>{{ userInfo.username }}</h3>
            <p>{{ userInfo.email }}</p>
            <p v-if="userInfo.roles">
              <el-tag v-for="role in userInfo.roles" :key="role" size="small" class="role-tag">
                {{ formatRole(role) }}
              </el-tag>
            </p>
          </div>
          
          <el-menu
            class="profile-menu"
            :default-active="activeMenu"
            @select="handleMenuSelect"
          >
            <el-menu-item index="basic">
              <i class="el-icon-user"></i>
              <span>基本资料</span>
            </el-menu-item>
            <el-menu-item index="security">
              <i class="el-icon-lock"></i>
              <span>安全设置</span>
            </el-menu-item>
            <el-menu-item index="sessions">
              <i class="el-icon-monitor"></i>
              <span>登录设备</span>
            </el-menu-item>
          </el-menu>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="16" :md="18">
        <el-card class="profile-content">
          <!-- 基本资料 -->
          <div v-if="activeMenu === 'basic'">
            <div class="section-header">
              <h2>基本资料</h2>
              <p>管理您的个人信息</p>
            </div>
            
            <el-form
              ref="basicInfoForm"
              :model="userForm"
              :rules="rules"
              label-width="100px"
              @submit.prevent="updateBasicInfo"
            >
              <el-form-item label="用户名">
                <el-input v-model="userInfo.username" disabled></el-input>
              </el-form-item>
              
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="userForm.email"></el-input>
              </el-form-item>
              
              <el-form-item label="姓名" prop="fullName">
                <el-input v-model="userForm.fullName"></el-input>
              </el-form-item>
              
              <el-form-item label="手机号" prop="phoneNumber">
                <el-input v-model="userForm.phoneNumber"></el-input>
              </el-form-item>
              
              <el-form-item label="学号">
                <el-input v-model="userInfo.examNumber" disabled></el-input>
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="updateBasicInfo" :loading="loading">
                  保存修改
                </el-button>
              </el-form-item>
            </el-form>
          </div>
          
          <!-- 安全设置 -->
          <div v-if="activeMenu === 'security'">
            <div class="section-header">
              <h2>安全设置</h2>
              <p>管理您的账号安全信息</p>
            </div>
            
            <el-form
              ref="passwordForm"
              :model="passwordFormData"
              :rules="passwordRules"
              label-width="120px"
              @submit.prevent="changePassword"
            >
              <el-form-item label="当前密码" prop="currentPassword">
                <el-input 
                  v-model="passwordFormData.currentPassword" 
                  type="password"
                  show-password
                ></el-input>
              </el-form-item>
              
              <el-form-item label="新密码" prop="newPassword">
                <el-input 
                  v-model="passwordFormData.newPassword" 
                  type="password"
                  show-password
                ></el-input>
              </el-form-item>
              
              <el-form-item label="确认新密码" prop="confirmPassword">
                <el-input 
                  v-model="passwordFormData.confirmPassword" 
                  type="password"
                  show-password
                ></el-input>
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="changePassword" :loading="loading">
                  修改密码
                </el-button>
              </el-form-item>
            </el-form>
          </div>
          
          <!-- 登录设备 -->
          <div v-if="activeMenu === 'sessions'">
            <div class="section-header">
              <h2>登录设备</h2>
              <p>查看和管理您的登录会话</p>
            </div>
            
            <div class="sessions-actions">
              <el-button type="danger" @click="logoutAllDevices" :loading="loading">
                登出所有设备
              </el-button>
            </div>
            
            <el-table
              :data="sessions"
              style="width: 100%"
              v-loading="sessionsLoading"
            >
              <el-table-column label="设备信息">
                <template #default="scope">
                  <div class="session-device">
                    <i class="el-icon-monitor"></i>
                    <span>{{ scope.row.deviceInfo || '未知设备' }}</span>
                    <el-tag size="small" type="success" v-if="scope.row.active">当前设备</el-tag>
                  </div>
                </template>
              </el-table-column>
              
              <el-table-column label="IP地址" prop="ipAddress"></el-table-column>
              
              <el-table-column label="登录时间">
                <template #default="scope">
                  {{ formatDate(scope.row.loginTime) }}
                </template>
              </el-table-column>
              
              <el-table-column label="最后活动时间">
                <template #default="scope">
                  {{ formatDate(scope.row.lastAccessTime) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import config from '../config'

export default {
  name: 'UserProfile',
  setup() {
    const store = useStore()
    const basicInfoForm = ref(null)
    const passwordForm = ref(null)
    const activeMenu = ref('basic')
    
    // 修正上传URL，确保使用动态计算的API基础URL
    const uploadUrl = computed(() => `${config.apiBaseUrl}/api/files/avatar`)
    
    const loading = computed(() => store.state.isLoading)
    const userInfo = computed(() => store.getters.getUserInfo)
    const sessions = ref([])
    const sessionsLoading = ref(false)
    
    // 表单数据
    const userForm = reactive({
      email: '',
      fullName: '',
      phoneNumber: ''
    })
    
    const passwordFormData = reactive({
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
    
    // 计算属性：确保用户头像路径完整
    const userAvatarUrl = computed(() => {
      return config.getFullResourceUrl(userInfo.value.avatarUrl);
    });
    
    // 验证规则
    const validatePhone = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else {
        const phoneReg = /^1[3-9]\d{9}$/
        if (!phoneReg.test(value)) {
          callback(new Error('请输入正确的手机号码'))
        } else {
          callback()
        }
      }
    }
    
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'))
      } else {
        if (passwordFormData.confirmPassword !== '') {
          passwordForm.value.validateField('confirmPassword')
        }
        callback()
      }
    }
    
    const validateConfirmPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入新密码'))
      } else if (value !== passwordFormData.newPassword) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }
    
    const rules = {
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      phoneNumber: [
        { validator: validatePhone, trigger: 'blur' }
      ]
    }
    
    const passwordRules = {
      currentPassword: [
        { required: true, message: '请输入当前密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, validator: validatePass, trigger: 'blur' },
        { min: 8, message: '密码长度不能少于8个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, validator: validateConfirmPass, trigger: 'blur' }
      ]
    }
    
    // 上传头像相关
    const uploadHeaders = computed(() => {
      return { Authorization: `Bearer ${store.state.token}` }
    })
    
    const beforeAvatarUpload = (file) => {
      const isImage = /\.(jpeg|jpg|png|gif)$/.test(file.name.toLowerCase())
      const isLt2M = file.size / 1024 / 1024 < 2
      
      if (!isImage) {
        ElMessage.error('头像只能是图片格式!')
        return false
      }
      
      if (!isLt2M) {
        ElMessage.error('头像大小不能超过 2MB!')
        return false
      }
      
      return true
    }
    
    const handleAvatarSuccess = (response) => {
      if (response.success) {
        // 确保路径格式正确，检查返回的头像路径
        let avatarPath = response.data;
        
        // 如果路径不符合预期格式，进行修正
        if (avatarPath && !avatarPath.startsWith('/users/avatars/') && !avatarPath.startsWith('http')) {
          // 如果路径以/uploads/users/avatars/开头，移除/uploads前缀
          if (avatarPath.startsWith('/uploads/users/avatars/')) {
            avatarPath = avatarPath.replace('/uploads', '');
          }
        }
        
        store.dispatch('updateAvatar', avatarPath)
        ElMessage.success('头像更新成功')
      } else {
        ElMessage.error(response.message || '头像上传失败')
      }
    }
    
    // 更新基本信息
    const updateBasicInfo = async () => {
      if (!basicInfoForm.value) return
      
      try {
        await basicInfoForm.value.validate(async (valid) => {
          if (valid) {
            const result = await store.dispatch('updateUserInfo', userForm)
            
            if (result.success) {
              ElMessage.success('个人资料更新成功')
            } else {
              ElMessage.error(result.message || '更新失败')
            }
          }
        })
      } catch (error) {
        ElMessage.error('操作异常，请稍后重试')
      }
    }
    
    // 修改密码
    const changePassword = async () => {
      if (!passwordForm.value) return
      
      try {
        await passwordForm.value.validate(async (valid) => {
          if (valid) {
            const result = await store.dispatch('changePassword', passwordFormData)
            
            if (result.success) {
              ElMessage.success('密码修改成功')
              passwordFormData.currentPassword = ''
              passwordFormData.newPassword = ''
              passwordFormData.confirmPassword = ''
              passwordForm.value.resetFields()
            } else {
              ElMessage.error(result.message || '密码修改失败')
            }
          }
        })
      } catch (error) {
        ElMessage.error('操作异常，请稍后重试')
      }
    }
    
    // 获取登录会话
    const fetchSessions = async () => {
      sessionsLoading.value = true
      try {
        const response = await axios.get('/api/auth/sessions', {
          headers: { Authorization: `Bearer ${store.state.token}` }
        })
        
        if (response.data.success) {
          sessions.value = response.data.data
        } else {
          ElMessage.error(response.data.message || '获取登录设备失败')
        }
      } catch (error) {
        ElMessage.error('获取登录设备信息失败')
      } finally {
        sessionsLoading.value = false
      }
    }
    
    // 登出所有设备
    const logoutAllDevices = async () => {
      try {
        const response = await axios.post('/api/auth/logout-all', null, {
          headers: { Authorization: `Bearer ${store.state.token}` }
        })
        
        if (response.data.success) {
          ElMessage.success('已成功登出所有设备')
          store.commit('CLEAR_AUTH')
          window.location.href = '/login'
        } else {
          ElMessage.error(response.data.message || '操作失败')
        }
      } catch (error) {
        ElMessage.error('操作失败，请稍后重试')
      }
    }
    
    // 菜单选择
    const handleMenuSelect = (index) => {
      activeMenu.value = index
      if (index === 'sessions') {
        fetchSessions()
      }
    }
    
    // 格式化角色名称
    const formatRole = (role) => {
      const roleMap = {
        'ROLE_ADMIN': '管理员',
        'ROLE_USER': '普通用户',
        'ROLE_TEACHER': '教师'
      }
      return roleMap[role] || role
    }
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '未知'
      
      const date = new Date(dateString)
      return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`
    }
    
    // 初始化表单数据
    const initFormData = () => {
      userForm.email = userInfo.value.email || ''
      userForm.fullName = userInfo.value.fullName || ''
      userForm.phoneNumber = userInfo.value.phoneNumber || ''
    }
    
    onMounted(() => {
      store.dispatch('fetchUserInfo').then(() => {
        initFormData()
      })
    })
    
    return {
      basicInfoForm,
      passwordForm,
      userInfo,
      userForm,
      passwordFormData,
      rules,
      passwordRules,
      activeMenu,
      loading,
      uploadHeaders,
      sessions,
      sessionsLoading,
      uploadUrl,
      
      handleMenuSelect,
      updateBasicInfo,
      changePassword,
      beforeAvatarUpload,
      handleAvatarSuccess,
      fetchSessions,
      logoutAllDevices,
      formatRole,
      formatDate,
      userAvatarUrl
    }
  }
}
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.profile-sidebar {
  margin-bottom: 20px;
}

.user-avatar {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.avatar-uploader {
  margin-top: 10px;
}

.user-info-summary {
  text-align: center;
  margin-bottom: 20px;
}

.user-info-summary h3 {
  margin-bottom: 5px;
}

.user-info-summary p {
  color: #606266;
  margin-bottom: 5px;
}

.role-tag {
  margin: 0 2px;
}

.profile-menu {
  border-right: none;
}

.profile-content {
  min-height: 500px;
}

.section-header {
  margin-bottom: 30px;
  border-bottom: 1px solid #e6e6e6;
  padding-bottom: 15px;
}

.section-header h2 {
  font-size: 20px;
  margin-bottom: 5px;
}

.section-header p {
  color: #909399;
  font-size: 14px;
}

.sessions-actions {
  margin-bottom: 20px;
  text-align: right;
}

.session-device {
  display: flex;
  align-items: center;
}

.session-device i {
  margin-right: 8px;
  font-size: 18px;
}

.session-device span {
  margin-right: 8px;
}

@media (max-width: 768px) {
  .profile-sidebar {
    margin-bottom: 20px;
  }
}
</style> 